<template>
	<view class="main-box">
		<view :style="{ height:headBarInfo.navBarHeight+'px'}" class="head-bar-box">
			<view
				:style="{height:headBarInfo.headBarContentHeight+'px',marginRight:headBarInfo.headBarContentRight+'px'}"
				class="head-bar-content-box">

				<image :style="{marginLeft:headBarInfo.menuRight + 'px'}" style="height: 32px;width: 32px;"
					@click="backClick" src="../../../static/nav-bar-icon-back.png"></image>

				<view style="display: flex;align-items: center;flex: 1;margin-left: 8px;">
					<image class="head-bar-image" :src="userInfo.avatar"></image>
					<text class="head-bar-text">{{userInfo.nickname}}</text>
				</view>
				<button class="focus-btn" :class="{ followed: userInfo.isFollow }" @click="toggleFollow(userInfo)">
					{{ userInfo.isFollow ? '已关注' : '关注' }}</button>
			</view>

		</view>

		<scroll-view scroll-y="true" style="width: 100%;background-color: white;" :scroll-y="true" @scroll="scroll"
			refresher-enabled="true" :refresher-triggered="triggered" @refresherrefresh="onLoadMore"
			:scroll-top="scrollTop"
			:style="{ height:scrollViewHeight+'px',marginTop:headBarInfo.navBarHeight+'px',marginBottom:bottomViewHeight+'px'}"
			ref="myScrollView">
			<view style="height: 12px;"></view>

			<view v-for="(item, index) in dataListChat" :key="item.id" id="myChatItemView">
				<view v-if="item.type===0" style="display: flex;flex-direction: row-reverse;margin-top: 2px;">
					<view style="width: 72pxpx;;margin-right: 16px;margin-left: 8px;">
						<image style="height: 48px;width: 48px;border-radius: 50%" :src="userInfo.myAvatar">
						</image>
					</view>
					<text
						style="word-wrap: break-word;word-break: break-all;white-space: pre-line;background-color: #2F6EF5;color: white;border-radius: 8px;margin-left: 84px;margin-top: 24px;font-weight: 500;
                    padding: 8px; word-wrap: break-word;word-break: break-all;white-space: pre-line;">{{item.content}}</text>
				</view>

				<view v-if="item.type===1" style="display: flex;margin-top: 6px    ;">
					<view style="width: 72pxpx;;margin-left: 16px;margin-right: 8px;">
						<image style="height: 48px;width: 48px;border-radius: 50%" :src="userInfo.avatar">
						</image>
					</view>
					<text
						style="word-wrap: break-word;word-break: break-all;white-space: pre-line;background-color: #F5F5F5;color: #181818;border-radius: 8px;margin-right: 84px;margin-top: 24px;font-weight: 500;
                    padding: 8px; word-wrap: break-word;word-break: break-all;white-space: pre-line;">{{item.content}}</text>
				</view>
			</view>


			<view style="height: 12px;"></view>
		</scroll-view>

		<view
			style="width: 100%;background-color: white;box-shadow:0 0px 30px 30px #0000000d;position: absolute;bottom: 0%;"
			id="myBottomView">
			<textarea style="margin: 12px 16px 12px 16px; background-color: white; ;width: auto;height: auto;
			border-radius: 12px;padding: 8px 66px  8px  12px;
			border: 1px solid #E5E5E5;" type="textarea" suffixIcon="search" placeholder="说点什么吧~" v-model="inputString"
				auto-height @linechange="setViewData()" maxlength="128" confirm-type=“send” @confirm="sendMessage">
			</textarea>
		</view>
	</view>
</template>

<script>
	import wsRequest from '@/utils/websocketUtil.js'
	import {
		getHistory,
		postSend
	} from '@/api/chat.js';
	import {
		postFollow
	} from '@/api/user.js'; // 引入登录接口
	export default {
		data() {
			return {
				socket: null,
				headBarInfo: {
					navBarHeight: 0, // 导航栏高度
					menuRight: 0, // 胶囊距右方间距（方保持左、右间距一致）
					menuTop: 0, // 胶囊距顶部间距
					menuHeight: 0, // 胶囊高度（自定义内容可与胶囊高度保证一致）

					headBarContentHeight: 0, //用来装载内容的盒子高度
					headBarContentRight: 0, //胶囊占据 的空间
				},
				scrollViewHeight: 0,
				bottomViewHeight: 0,

				//页面样式交互数据
				triggered: false,
				scrollTop: 0,
				old: {
					scrollTop: 0
				},
				targetId: 0,
				//数据
				pageNo: 1,
				inputString: '',
				userInfo: {},
				dataListChat: []
			}
		},
		mounted() {
			let userId = uni.getStorageSync('userId');
			this.socket = new wsRequest(`wss://www.aaxing14.top:8101/imserver/${userId}`, 5000);
			let data = {
				value: "传输内容",
				method: "方法名称"
			};
			this.socket.send(data);
			this.watchSocket();
		},
		onLoad(options) {
			if (options.targetId) {
				this.targetId = options.targetId; // 获取页面传递数据
				console.log("获取页面传递数据", this.targetId)
				this.getHistory(this.pageNo, 10, this.targetId)
			}
			// 获取系统信息
			const systemInfo = wx.getSystemInfoSync();
			// 胶囊按钮位置信息
			const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
			// 导航栏高度 = 状态栏高度 + 44
			this.headBarInfo.navBarHeight = systemInfo.statusBarHeight + 44;
			this.headBarInfo.menuRight = systemInfo.screenWidth - menuButtonInfo.right;
			this.headBarInfo.menuTop = menuButtonInfo.top;
			this.headBarInfo.menuHeight = menuButtonInfo.height;
			this.headBarInfo.headBarContentHeight = (this.headBarInfo.navBarHeight - this.headBarInfo.menuHeight - this
				.headBarInfo.menuTop) * 2 + this.headBarInfo.menuHeight;
			this.headBarInfo.headBarContentRight = menuButtonInfo.width + this.headBarInfo.menuRight * 2;
		},
		onReady() {
			this.setViewData()
			this.goBottom()
		},
		onShow() {},
		  onUnload() {
		    this.socket.close(); // 页面卸载时关闭 WebSocket
		  },
		methods: {
			async toggleFollow(item) {
				item.isFollow = !item.isFollow;
				// const userId = uni.getStorageSync('userId');
				// 在此处理实际的关注或取消关注逻辑，如发起 API 请求
				const data = {
					followedId: this.targetId,
					isFollow: item.isFollow,
				};
				await postFollow(data)
					.then(response => {
						if (response.code == 200) {
							this.userInfo = response.data;
						} else {

						}
					})
					.catch(error => {
						console.error('点赞失败:', error);
					});
			},
			watchSocket() {
				// 接收消息
				this.socket.getMessage(res => {
					console.log("聊天消息", res)
					this.dataListChat.push({
						type: 1,
						content: res.data
					})
					this.goBottom();
				})
			},
			setViewData() {
				let that = this
				this.$nextTick(function() {

					const systemInfo = wx.getSystemInfoSync();
					// 胶囊按钮位置信息
					const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
					var query = wx.createSelectorQuery();
					query.select('#myBottomView').boundingClientRect();

					query.exec(function(res) {
						//res就是 所有标签为mjltest的元素的信息 的数组
						//取高度
						that.bottomViewHeight = res[0].height
						console.log("bottomHeight : " + that.bottomViewHeight)
						that.scrollViewHeight = systemInfo.screenHeight - that.headBarInfo.navBarHeight -
							that.bottomViewHeight
						// console.log("this.scrollViewHeight", that.scrollViewHeight)
					});
				})
			},
			async getHistory(pageNo, pageSize, targetId) {
				await getHistory(pageNo, pageSize, targetId)
					.then(response => {
						if (response.code == 0) {
							this.userInfo = response.data;
							this.dataListChat = response.data.chatListVO;
						} else {
							uni.showToast({
								title: response.data.message,
								icon: 'none'
							});
						}
					})
					.catch(error => {
						console.error('获取失败:', error);
					});
			},
			sendMessage() {
				if (this.inputString.length > 0) {
					const data = {
						targetId: this.targetId,
						content: this.inputString
					}
					postSend(data)
						.then(response => {
							console.log("聊天记录请求发送", response)
							if (response.code == 0) {
								this.dataListChat.push({
									type: 0,
									content: this.inputString
								})
								this.inputString = ''
								// 在下次 DOM 更新后确保滚动到最底部
								this.$nextTick(() => {
									this.goBottom();
								});
							} else {
								uni.showToast({
									title: response.data.message,
									icon: 'none'
								});
							}
						})
				}


			},
			scroll(e) {
				this.old.scrollTop = e.detail.scrollTop
			},
			goBottom() {
				const query = this.createSelectorQuery(); // 使用 uni-app 兼容的方法
				query.selectAll('#myChatItemView').boundingClientRect();
				query.exec((res) => {
					if (res[0]) {
						let bottomHeight = res[0].reduce((acc, item) => acc + item.height, 0);
						this.scrollTop = bottomHeight; // 设置 scrollTop 到底部
						console.log("scrollTop:", bottomHeight);
					}
				});
			},
			backClick() {
				uni.navigateBack()
			},
			onLoadMore() {
				this.triggered = true;
				this.pageNo = this.pageNo + 1;
				getHistory(this.pageNo, 10, this.targetId)
					.then(response => {
						if (response.code == 0) {
							const List = response.data.chatListVO;
							this.dataListChat.unshift(...List);
							this.triggered = false;
						} else {
							uni.showToast({
								title: response.data.message,
								icon: 'none'
							});
						}
					})
					.catch(error => {
						console.error('获取失败:', error);
					});
				// setTimeout(() => {
				// this.dataListChat.unshift({
				// 	type: 0,
				// 	content: "过往信息1"
				// }, {
				// 	type: 1,
				// 	content: "过往信息2！"
				// }, {
				// 	type: 1,
				// 	content: "过往信息3！"
				// })
				// 	// console.log("unshift",this.dataListChat)
				// 	this.triggered = false;
				// }, 1000)
			},

		}
	}
</script>

<style>
	.main-box {
		position: absolute;
		bottom: 0%;
		top: 0%;
		right: 0%;
		left: 0%;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.head-bar-box {
		top: 0%;
		position: absolute;
		width: 100%;
		background-color: white;
		display: flex;
		flex-direction: column-reverse;
		border-bottom: 1px solid #D9D9D9
	}

	.head-bar-content-box {
		background-color: #fff;
		align-items: center;
		display: flex;
		justify-content: space-between;
	}

	.head-bar-image {
		height: 32px;
		width: 32px;
		border-radius: 50%;
		display: inline-table;
	}

	.head-bar-text {
		color: #181818;
		margin-left: 12rpx;
		text-overflow: ellipsis;
		overflow: hidden;
		-webkit-box-orient: vertical;
		display: -webkit-box;
		-webkit-line-clamp: 1;
		text-align: start;
		font-size: 17px;
		font-style: normal;
		font-weight: 500;
		line-height: 150%;
	}


	.focus-btn {
		margin: 0 14rpx 0 14rpx;
		border-radius: 50%;
		color: #FFF;
		background-color: #2F6EF5;
		font-size: 14px;
		width: 60px;
		height: 28px;
		flex-shrink: 0;
		align-items: center;
		justify-content: center;
		border-radius: 20px;
		display: flex;
		transition: background-color 0.3s, color 0.3s, border 0.3s;
		line-height: 28px; /* 确保文字垂直居中 */
	}

	.focus-btn.followed {
		background-color: transparent;
		/* 关注后的背景透明，模拟镂空效果 */
		color: #ACACAC;
		/* 文字颜色变为灰色 */
		border: 1px solid #ACACAC;
		/* 灰色边框 */
		font-size: 24rpx;
		padding: 10rpx 20rpx;
		line-height: 28px; /* 保持垂直居中 */
		/* 调整 padding 保持一致 */
	}

	,



	.send-btn {
		font-size: 14px;
		position: absolute;
		color: #fff;
		background-color: #DDD;
		font-size: 14px;
		width: 60px;
		height: 28px;
		flex-shrink: 0;
		align-items: center;
		display: flex;
		border-radius: 8px;
		display: flex;
		bottom: 17px;
		right: 19px;

	}
</style>